package com.dbs.donatebooksystem.controller;

import com.dbs.donatebooksystem.Service.BooksService;
import com.dbs.donatebooksystem.pojo.Book;
import com.dbs.donatebooksystem.pojo.PageBean;
import com.dbs.donatebooksystem.pojo.Result;
import com.dbs.donatebooksystem.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin(origins = "http://localhost:8080", originPatterns = "http://localhost:8081")
public class BooksController {
    private static final Logger log1 = LoggerFactory.getLogger(BooksController.class);
    @Autowired
    private BooksService booksService;

    @PostMapping("/InsertBook")
    public Result BooksAdd(@RequestBody Book book) {
        log.info("发布书籍,{}", book);
        boolean b = booksService.InsertBooks(book);
        if (b) {
            return Result.success("发布成功");
        }
        return Result.error("发布失败");
    }

    @GetMapping("/BooksAllSelect")
    public Result BooksAllSelect(String bookname, String category) {
        log.info("查询书籍，{}，{}", bookname, category);
        List<Book> bookList = booksService.SelectBooks(bookname, category);
        return Result.success(bookList);
    }

    @GetMapping("/books")
    public Result page(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "1000") Integer pageSize, String bookname, String category) {
        log.info("分页函数的参数：{},{},{},{}", page, pageSize, bookname, category);
        PageBean pageBean = booksService.pageBean(page, pageSize, bookname, category);
        return Result.success(pageBean);
    }

    @GetMapping("/adminBooks")
    public Result page_0(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "1000") Integer pageSize, String bookname, String category) {
        log.info("分页函数的参数：{},{},{},{}", page, pageSize, bookname, category);
        PageBean pageBean = booksService.pageBean(page, pageSize, bookname, category);
        return Result.success(pageBean);
    }

    @GetMapping("/category")
    public Result category() {
        log.info("查询书本类型");
        List<List<Object>> list = booksService.selectCategoryNum();
        return Result.success(list);
    }

    @PostMapping("/UpdateBook")
    public Result UserUpdate(@RequestBody Book book) {
        log.info("书籍信息更新", book);
        booksService.UpdateBook(book);
        return Result.success("更新成功");
    }

    @DeleteMapping ("/deleteBook")
    public Result deleteBook(@RequestParam Integer id) {
        log.info("删除书本的Id:,{}", id);
        booksService.deleteBook(id);
        return Result.success("删除成功");
    }

    @PostMapping("/InsertBooks")
    public Result BooksAdd(@RequestParam("file") MultipartFile file, @RequestBody Book book) {
        try {
            log.info("发布书籍, {}", book);
            // 处理文件上传
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            // 保存文件到服务器中
            byte[] bytes = file.getBytes();
            Path path = Paths.get("uploads/" + fileName);
            try {
                Files.write(path, bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 将文件路径设置到book对象中
            book.setPhotoUrl("/uploads/" + fileName);

            // 调用服务层插入书籍信息
            boolean b = booksService.InsertBooks(book);
            if (b) {
                return Result.success("发布成功");
            }
            return Result.error("发布失败");
        } catch (IOException ex) {
            log.error("上传文件失败", ex);
            return Result.error("上传文件失败");
        }
    }

    @GetMapping("/SearchBook")
    public Result SearchBook(Book searchBook) {
        if (searchBook == null){
            List<Book> books = booksService.SelectBooks(null, null);
            return Result.success(books);
        }
        log.info("查询书籍，{}，{},{},{},{}", searchBook.getBookname(), searchBook.getConditions(), searchBook.getPageCount(), searchBook.getBooksCode(), searchBook.getCategory());
        List<Book> bookList = booksService.SearchBooks(searchBook);
        return Result.success(bookList);
    }

    @GetMapping("/selectBookById")
    public Result selectBookById(@RequestParam Integer id){
        log.info("要查询的书籍id是:{}",id);
        Book book = booksService.selectBookById(id);
        return Result.success(book);
    }
}
